package org.apache.ibatis.session;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class SqlSession {
	
	private Connection conn;
	public Connection getConn() {
		return conn;
	}
	public void setConn(Connection conn) {
		this.conn = conn;
	}

	private Map<String,SelectStatement> selectStatementMap = new HashMap<String,SelectStatement>();
	
	
	
	public Map<String, SelectStatement> getSelectStatementMap() {
		return selectStatementMap;
	}
	public void setSelectStatementMap(Map<String, SelectStatement> selectStatementMap) {
		this.selectStatementMap = selectStatementMap;
	}
	public Object selectOne(String objectStr,int p){
		System.out.println("准备操作数据库，连接："+conn);
		SelectStatement selectStatement = selectStatementMap.get(objectStr);
		//System.out.println(selectStatement);
		String sql = selectStatement.getSqltext();
		String parameterType = selectStatement.getParameterType();
		String resultType = selectStatement.getResultType();
		try {
			PreparedStatement prepareStatement = conn.prepareStatement(sql);
			//System.out.println("返回的类型："+resultType);
			if (parameterType.equals("int")){
				prepareStatement.setInt(1, p);
			}
			Class c = Class.forName(resultType);
			Object object = c.newInstance();//Object object = new User();
			Method[] methods = c.getMethods();
			ResultSet rs = prepareStatement.executeQuery();
			if(rs.next()){
				
				for(Method m:methods){
					String methodName = m.getName();
					if ( methodName.indexOf("set")!=-1){
						String methodName_noSet = methodName.substring(3);//截取掉set字眼
						if (m.getParameterTypes()[0]== Integer.class ){
							m.invoke(object, rs.getInt(methodName_noSet));
						}
						if (m.getParameterTypes()[0]== String.class ){
							m.invoke(object, rs.getString(methodName_noSet));
						}
					}
				}

				
			}
			rs.close();
			prepareStatement.close();
			
			
			
			
			
			return object;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void commit(){
		System.out.println("没有使用事务，忽略commit");
	}
	
	public void close(){
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("成功关闭连接,session变成不可用");
	}
}
